package algorithm.leetcode.simple;

/**
 * 给定一个字符串 s，找到 s 中最长的回文子串
 *
 * @author jack.wu
 * @version 1.0
 * @date 2020/8/17
 */
public class Question5And9 {

    public static void main(String[] args) {
        Question5And9 substring = new Question5And9();
        String str = "cbbd";
        String palindrome = substring.longestPalindrome(str);
        System.out.println(palindrome);

//        System.out.println(substring.isPalindrome(12321));


    }

    public String longestPalindrome(String s) {
        if (s == null || s.length() <= 1) {
            return s;
        }
        int maxLen = 1;
        int start = 0;

        char[] charArray = s.toCharArray();
        for (int i = 0; i < charArray.length - 1; i++) {
            for (int j = i + 1; j < charArray.length; j++) {
                if ((j - i + 1) > maxLen && isPalindrome(charArray, i, j)) {
                    maxLen = j - i + 1;
                    start = i;
                }
            }
        }

        return s.substring(start, start + maxLen);
    }

    private boolean isPalindrome(char[] charArray, int left, int right) {
        while (left < right) {
            if (charArray[left] != charArray[right]) {
                return false;
            }
            left++;
            right--;
        }
        return true;
    }


    public boolean isPalindrome(int x) {
        if (x < 0) {
            return false;
        }
        // 除数
        int div = 1;
        while (x / div >= 10) {
            div *= 10;
        }

        while (x > 0) {
            int left = x / div;
            int right = x % 10;
            if (left != right) {
                return false;
            }
            // 找到下一位数
            x = (x % div) / 10;
            // 由于找下一位数的时候除了10 所以这里需要 / （10*10）
            div /= 100;
        }
        return true;
    }


}
